package com.example.ucsur;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
	
public class SearchActivity extends Activity {

	
	//Declare variables needed at class level.
	Button buttonGetData = null;
	int arraylength;
	EditText editTextSearchString = null;
	Button textViewFirstName = null;
	TextView textViewLastName = null;
	TextView textViewMarket = null;
	JSONArray jsonArrayFromHttp = new JSONArray();
	JSONObject jsonObjectFromHttp = new JSONObject();
	JSONObject jsonPassedToActivity = new JSONObject();
	String result;  
	String strPropertyNumber;
	String strLastName;
	String strPropertyAddress;
	double FairMarketTotal;
	Button buttonsFromResults[] = new Button[50];
	LinearLayout nm;
    LayoutParams nn;
	
	//OnCreate method for when activity starts.
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		
		
		//Set Field Variables From XML
		buttonGetData = (Button) findViewById(R.id.buttonGetData);
		editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
		nm = (LinearLayout) findViewById(R.id.linearlayout);
	    nn = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		
		//Setup the Button's OnClickListener
		buttonGetData.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//Get the data
				InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE); 
				inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                           InputMethodManager.HIDE_NOT_ALWAYS);
				DoPOST mDoPOST = new DoPOST(SearchActivity.this, editTextSearchString.getText().toString());
				mDoPOST.execute("");
				buttonGetData.setEnabled(false);
				/*for (int k = 0; k < 25; k++)
				{
					nm.removeView(buttonsFromResults[k]);
				}*/
			}}
		);
	}
	
	
	/*Create Options Menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}*/

	public class DoPOST extends AsyncTask<String, Void, Boolean>{

		
		//Set up any POST variables we need.
		Context mContext = null;
		String strAddressToSearch = "";
		String strZipToSearch = "";
		String choice1 = new String("Address");
		String choice2 = new String("ZipCode");
		int fieldCode;
		Button buttonsFromResults[] = new Button[50];
		//Button getNextButton = new Button(mContext);
		Exception exception = null;
		Exception exception1;
		
		
		//Default constructors.
		DoPOST(Context context, String toSearch){
			mContext = context;
			strAddressToSearch = toSearch;
		}
		

		@Override
		protected Boolean doInBackground(String... arg0) {

			try{

				//Setup the parameters
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("FirstAddressToSearch", strAddressToSearch));
				nameValuePairs.add(new BasicNameValuePair("FirstZipToSearch", strZipToSearch));
				//Add more parameters as necessary

				//Create the HTTP request
				HttpParams httpParameters = new BasicHttpParams();

				//Setup timeouts
				HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
				HttpConnectionParams.setSoTimeout(httpParameters, 15000);			

				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost("http://bhunsaker.pairserver.com/login1.php");
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));        
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				result = EntityUtils.toString(entity);
				//Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
				// Create a JSON array from the request response
				try
				{
					jsonArrayFromHttp = new JSONArray(result);
					arraylength = jsonArrayFromHttp.length();
				}
				//Catch exception that we only get one result. Use a JSON array instead.
				catch (Exception e)
				{
					jsonObjectFromHttp = new JSONObject(result);
				}
				
				
			}catch (Exception e){
				Log.e("ClientServerDemo", "Error:", e);
				exception = e;
			}

			return true;
		}

		//On valid execute, run method to create buttons for each result.
		@Override
		protected void onPostExecute(Boolean valid){
			//Update the UI
			createButtons();
			if(exception != null){
				Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
				//Toast.makeText(mContext, strAddressToSearch, Toast.LENGTH_LONG).show();
			}
		}

	}
	int n = 0;
	
	//Create array of buttons, each representing one result in our search.
	public void createButtons()
	{
		//Setup button array variables needed.
	    int x = 0;
	    n = 0;
	    nm.removeAllViewsInLayout();
	    //25 Buttons at a time.
		while (n < arraylength && n < 25)
		{
			try {
				jsonObjectFromHttp = jsonArrayFromHttp.getJSONObject(n);
				strPropertyNumber = jsonObjectFromHttp.getString("PropertyHouseNum");
				strPropertyAddress = jsonObjectFromHttp.getString("PropertyAddress");
				FairMarketTotal = jsonObjectFromHttp.getDouble("FairMarketTotal");
				Button button = new Button(this);
				buttonsFromResults[x] = button;
				
				buttonsFromResults[x].setText(strPropertyNumber + ": " + strPropertyAddress + ":::   " + FairMarketTotal);
				buttonsFromResults[x].setId(n);
				nm.addView(buttonsFromResults[x], nn);
				n = n + 1;
				x = x + 1;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		buttonGetData.setEnabled(true);
		}
		//Setup onclick listeners.
		createClick();
	}
	
	
	public void createClick(){
		
		for (int i = 0; i < (arraylength - 1) && i < 25; i++) {
			final Button clickableButtonsFromResults = buttonsFromResults[i];
			clickableButtonsFromResults.setId(buttonsFromResults[i].getId());
   			clickableButtonsFromResults.setOnClickListener(new View.OnClickListener() {
				
   				
   				//On click, send data to map activity to draw.
				@Override
				public void onClick(View v) {
					try {
						jsonPassedToActivity = jsonArrayFromHttp.getJSONObject(clickableButtonsFromResults.getId());
						String jsonStringPassedToActivity = jsonPassedToActivity.toString();
						
						//Breaks address down into (House Number) + (Street Name) + (Zip Code) and then adds to intent.
						String breakAddress = jsonPassedToActivity.getString("PropertyAddress").replace(" ", "+");
						String address = new String((jsonPassedToActivity.getString("PropertyHouseNum") + "+" + (breakAddress)) + "+" +(jsonPassedToActivity.getString("PropertyZip")));
						
						
						Intent intent = new Intent(getBaseContext(), MapSearchActivity.class);
						intent.putExtra("address", address);
						intent.putExtra("dataFromActivity", jsonStringPassedToActivity);
						startActivity(intent);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}				


				}
			});
		}
	}
}